<template>
  <!-- 在template部分新增文件管理弹窗 -->
  <el-dialog
      :close-on-click-modal="false"
      model-value="fileDialogVisible"
      width="80%"
      :before-close="handleFileDialogClose">
    <template #header="{  titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">
          文件路径:&nbsp;{{ currentPath }}
        </h4>
      </div>
    </template>
    <div class="file-manager-container">
      <!-- 文件操作工具栏 -->
      <div class="file-toolbar">
        <el-button type="primary" @click="refreshFileList">刷新</el-button>
        <el-upload
            name="files"
            :headers="headers"
            :http-request="uploadFile"
            :on-progress="handleProgress"
            :on-error="handleError"
            action="#"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :data="uploadActionData"
        >
          <el-button type="warning">上传文件</el-button>
        </el-upload>
        <el-button type="primary" @click="returnToTheSuperiorDirectory">上级目录</el-button>
      </div>
      <!-- 展示下载进度条 -->
      <div class="progress-container" v-if="Progress.visible">
        <el-progress
            :percentage="Progress.percent"
            :status="Progress.status"
            :stroke-width="16"
            striped
            striped-flow
            :format="() => ''"
        />
        <el-row class="progress-info">
          <el-text>{{ Progress.fileName }}</el-text>
          <el-text>正在上传{{ Progress.percent }}%</el-text>
          <el-text>{{ Progress.speed }}/s</el-text>
          <el-text type="warning" v-if="Progress.remotePercent">正在分发到服务器{{ Progress.remotePercent }}%</el-text>
        </el-row>
      </div>
      <!-- 文件列表 -->
      <el-table
          :data="fileList"
          height="500" style="width: 100%; margin-top: 15px"
          @row-click="handleFileClick">
        <el-table-column prop="name" label="文件名">
          <template #default="{row}">
            <div class="file-item">
              <el-icon :size="20" style="margin-right: 8px">
                <FolderOpened v-if="row.is_dir"/>
                <Document v-else/>
              </el-icon>
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="120">
          <template #default="{row}">
            {{ row.is_dir ? '-' : formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="mtime" label="修改时间" width="180"/>
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button
                v-if="!row.is_dir"
                @click="downloadFile(row)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script setup>
import {Document, FolderOpened} from "@element-plus/icons-vue";
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";
import Cookies from "js-cookie";

const props = defineProps({
  progressData: {
    type: Number,
    default: 0,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
  sessionsData: {
    type: Array,
    default: () => [],
    required: true
  },
  currentSessionIDData: {
    type: String,
    default: '',
    required: true
  },
  activeSessionData: {
    type: String,
    default: '',
    required: true
  },
  connectInfo: {
    type: Object,
    required: true,
    default: () => ({}), // 默认空对象
  },
})

const Progress = ref({
  remotePercent: 0,
  visible: false,
  percent: 0,
  speed: '0KB',
  fileName: '',
  status: 'success'
})

const uploadActionData = ref({
  host_id: 0,
  path: '',
  op_type: 'upload',
})

const fileList = ref([])
const currentPath = ref('/tmp')
// 终端会话管理
const sessions = ref([])
const currentSessionID = ref('')
const activeSession = ref('')
const uploadAction = ref(null)

const refreshFileList = async () => {
  const sessionIndex = sessions.value.findIndex(s => s.id === currentSessionID.value)
  const session = sessions.value[sessionIndex]

  uploadAction.value = `/host/terminal/file/upload?host_id=${session.host.id}`
  uploadActionData.value.host_id = session.host.id
  uploadActionData.value.path = currentPath.value
  const res = await requestUtil.post('/host/terminal/file', {
    host_id: session.host.id,
    op_type: 'list',  // 新增参数
    session_id: activeSession.value,
    path: currentPath.value
  })
  if (res.data.code === 200) {
    fileList.value = res.data.data.map(item => ({
      ...item,
    }))
  } else if (res.data.code === 404) {
    if (props.connectInfo.server_type === 2) {
      currentPath.value = `C:\\Users\\${props.connectInfo.user}\\Downloads`
    } else {
      currentPath.value = '/tmp'
    }
    ElMessage.error(res.data.msg)
    await refreshFileList()
  } else {
    ElMessage.error(res.data.msg)
  }
}

const uploadFile = async ({file}) => {
  const startTime = Date.now()

  const formData = new FormData();
  formData.append('files', file);
  formData.append('host_id', uploadActionData.value.host_id);
  formData.append('path', uploadActionData.value.path);
  formData.append('op_type', uploadActionData.value.op_type);
  Progress.value.fileName = file.name
  Progress.value.remotePercent = 0

  // 计算速度（字节/秒）
  try {
    await requestUtil.post(uploadAction.value, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        Progress.value.visible = true

        const loaded = progressEvent.loaded
        const currentTime = Date.now()

        const timeDiff = (currentTime - startTime) / 1000

        // 计算上传进度
        Progress.value.percent = Math.min(100, Math.round((progressEvent.loaded * 100) / file.size));
        Progress.value.speed = (loaded / timeDiff / 1024).toFixed(1) + 'KB'
      },
    });
  } catch (error) {
    ElMessage.error('上传失败:', error)
  }
};

const headers = ref({
  Authorization: Cookies.get('token')
})

// 上传失败钩子
const handleError = () => {
  ElMessage.error('上传失败:')
  Progress.value.percent = 0;  // 重置进度条
  Progress.value.visible = false;  // 重置进度条
};

// 上传进度钩子
const handleProgress = (event) => {
  console.log('上传进度:', event.percent);
};

const handleUploadSuccess = () => {
  ElMessage.success('上传成功')
  Progress.value.percent = 0;  // 重置进度条
  Progress.value.visible = false
  refreshFileList()
}

const beforeUpload = (file) => {
  if (file.size > 1024 * 1024 * 1000) { // 100MB限制
    ElMessage.error('文件大小不能超过100MB')
    return false
  }
  return true
}

const downloadFile = async (file) => {
  const sessionIndex = sessions.value.findIndex(s => s.id === currentSessionID.value)
  const session = sessions.value[sessionIndex]
  const link = document.createElement('a')
  link.download = file.name
  // link.style.display = 'none'
  link.href = `${process.env.VUE_APP_BASE_API}host/terminal/file?host_id=${session.host.id}&path=${encodeURIComponent(currentPath.value)}&filename=${encodeURIComponent(file.name)}`
  // link.setAttribute('download', file.name)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.warning('开始下载文件，请勿重复点击')
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}


const handleFileClick = (row) => {
  if (row.is_dir) {
    if (props.connectInfo.server_type === 2) {
      currentPath.value = `${currentPath.value}\\${row.name}`.replace('\\\\', '\\')
    } else {
      currentPath.value = `${currentPath.value}/${row.name}`.replace('//', '/')
    }
    refreshFileList()
  }
}

const returnToTheSuperiorDirectory = () => {
  // 处理路径的逻辑
  if (props.connectInfo.server_type === 2) {
    const parts = currentPath.value.split('\\').filter(Boolean) // 分割并过滤空值
    if (parts.length > 1) {
      parts.pop() // 移除最后一项
    }
    currentPath.value = parts.join('\\')
  } else {
    const parts = currentPath.value.split('/').filter(Boolean) // 分割并过滤空值
    if (parts.length > 1) {
      parts.pop() // 移除最后一项
    }
    currentPath.value = '/' + parts.join('/')
  }


  refreshFileList()
};

const handleFileDialogClose = (done) => {
  currentPath.value = '/tmp'
  done()
  fileList.value = []
}

watch(
    () => props.dialogVisible,
    () => {
      if (props.dialogVisible === true) {
        Progress.value = {
          visible: false,
          percent: 0,
          speed: '0KB',
          fileName: '',
          srcDialogStatus: 'success'
        }
        sessions.value = props.sessionsData
        if (props.connectInfo.server_type === 2) {
          currentPath.value = `C:\\Users\\${props.connectInfo.user}\\Downloads`
        } else {
           currentPath.value = '/tmp'
        }
        refreshFileList()
      }
    }
)
// 添加对 currentPath 的监听
watch(currentPath, (newVal) => {
  if (newVal) {
    // 添加路径参数
    uploadActionData.value.path = currentPath.value
  }
})
// 添加对 props 的监听
watch(() => props,
    (newProps) => {
      Progress.value.remotePercent = newProps.progressData
      currentSessionID.value = newProps.currentSessionIDData
      activeSession.value = newProps.activeSessionData
    }, {deep: true, immediate: true}) // 深度监听 + 初始执行
</script>

<style scoped lang="scss">
.file-toolbar {
  display: flex;
  align-items: center;
  gap: 15px;
  padding-bottom: 15px;
  /*  border-bottom: 1px solid #eee;*/
}

.file-manager-container {
  padding: 15px;
}

.progress-container {
  margin: 15px 0;
  padding: 10px;
  /*background: #f8f9fa;*/
  border-radius: 4px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

/*.file-item:hover {
  background-color: #f5f7fa;
}*/
</style>